package com.bjgzy.rating.mvp.ui.fragment;

import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.bjgzy.rating.R;
import com.bjgzy.rating.R2;
import com.bjgzy.rating.mvp.ui.adapter.RecordListenAdapter;
import com.blankj.utilcode.util.ObjectUtils;
import com.eduhzy.ttw.commonres.utils.RxUtil;
import com.eduhzy.ttw.commonsdk.core.RouterHub;
import com.eduhzy.ttw.commonsdk.entity.EntriesDetailData;
import com.jess.arms.base.BaseFragment;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.mvp.IView;
import com.jess.arms.utils.ArmsUtils;
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog;

import java.io.IOException;
import java.util.List;

import butterknife.BindView;

import static com.jess.arms.utils.Preconditions.checkNotNull;

/**
 * @author xubo
 * @date 2018-9-10 11:45:43
 */
@Route(path = RouterHub.APP_AUDIOPLAYFRAGMENT)
public class AudioPlayFragment extends BaseFragment implements IView {
    RecordListenAdapter mAdapter;

    RecyclerView.LayoutManager layoutManager;
    @BindView(R2.id.rv_list)
    RecyclerView rvList;
    private List<EntriesDetailData.AttachmentListBean> dataList;
    private MediaPlayer mediaPlayer;
    private int mLastPosition=-1;

    public static AudioPlayFragment newInstance() {
        AudioPlayFragment fragment = new AudioPlayFragment();
        return fragment;
    }

    @Override
    public void setupFragmentComponent(@NonNull AppComponent appComponent) {
    }

    @Override
    public View initView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.rating_fragment_audio_play, container, false);
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        mediaPlayer = new MediaPlayer();
        layoutManager = new LinearLayoutManager(getActivity());
        mAdapter = new RecordListenAdapter(R.layout.rating_record_play_item, dataList);
        rvList.setLayoutManager(layoutManager);
        rvList.setAdapter(mAdapter);
        //去掉recyclerview notifyItemChanged 闪烁
        rvList.getItemAnimator().setChangeDuration(0);
        mAdapter.setOnItemClickListener((adapter, view, position) -> {
            EntriesDetailData.AttachmentListBean dataBean = mAdapter.getData().get(position);
            if (dataBean.isPlay()) {
                dataBean.setPlay(false);
                dataBean.setShowloading(false);
                mediaPlayer.stop();
                mediaPlayer.release();
                mAdapter.notifyItemChanged(position);
            } else {
                dataBean.setShowloading(true);
                mAdapter.notifyItemChanged(position);
                //处理上次播放未停止条目
                if (mLastPosition >= 0) {
                    mAdapter.getData().get(mLastPosition).setPlay(false);
                    mAdapter.getData().get(mLastPosition).setShowloading(false);
                    mAdapter.notifyItemChanged(mLastPosition);
                }
                this.mLastPosition = position;
                doPlayVoice(dataBean, position);
            }
        });
    }

    private void doPlayVoice(EntriesDetailData.AttachmentListBean bean, int position) {
        if (mediaPlayer == null) {
            mediaPlayer = new MediaPlayer();
        }
        // 为解决第二次播放时抛出的IllegalStateException，这里做了try-catch处理
        boolean isPlaying = false;
        try {
            isPlaying = mediaPlayer.isPlaying();
        } catch (IllegalStateException e) {
            mediaPlayer = null;
            mediaPlayer = new MediaPlayer();
        }

        if (isPlaying) {
            mediaPlayer.stop();
            mediaPlayer.release();
            mediaPlayer = null;
            mLastPosition = -1;
            mediaPlayer = new MediaPlayer();
        }
        try {
            mediaPlayer.setDataSource(bean.getResUrl());
            mediaPlayer.setOnPreparedListener(mp -> {
                bean.setPlay(true);
                mp.start();
                bean.setShowloading(false);
                mAdapter.notifyItemChanged(position);
            });
            // Prepare to async playing
            mediaPlayer.prepareAsync();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        mLastPosition = position;

        mediaPlayer.setOnCompletionListener(mp -> {
            /* 在目前的代码结构下，mp.release()生效(即设nativeContext=0)了，mp = null却未生效，
             * 导致在下一次播放语音（即下次调用doPlayVoice）时，mp对象不为null，而nativeContext
             * 却已经被release掉了，于是在执行mp.isPlaying()时就发生了IllegalStateException，为什么
             * 会发生这样【mp.release()生效了，mp = null却未生效】的状况，原因暂未查明，为解决该异常
             * 在doPlayVoice方法的开头mp.isPlaying()处加上了try-catch语句，发生异常时即执行mp = null;
             * mp = new MediaPlayer()两句，以恢复mp的状态为正常，效果是一样的。
             */
            bean.setPlay(false);
            bean.setShowloading(false);
            mAdapter.notifyItemChanged(position);
            mp.release();
            mp = null;
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (!ObjectUtils.isEmpty(mediaPlayer)) {
            try {
                mediaPlayer.stop();
                mediaPlayer.release();
                mediaPlayer = null;
            } catch (IllegalStateException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        if (!ObjectUtils.isEmpty(mediaPlayer)) {
            try {
                if (mLastPosition >= 0) {
                    mAdapter.getData().get(mLastPosition).setPlay(false);
                    mAdapter.getData().get(mLastPosition).setShowloading(false);
                    mAdapter.notifyItemChanged(mLastPosition);
                }
                mediaPlayer.stop();
            } catch (IllegalStateException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void setData(@Nullable Object data) {
        dataList = (List<EntriesDetailData.AttachmentListBean>) data;

    }


    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        RxUtil.showTipDialog(getActivity(), QMUITipDialog.Builder.ICON_TYPE_NOTHING, message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {

    }
}
